
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
import * as process from "process";
const db = cloud.database()
const _ = db.command
export default async function (ctx: FunctionContext) {
  let code = ctx.body.code
  if (nw.util.isNull(code)){
    return fail("参数不合法")
  }
  //请求微信服务器返回具体的数据结构
  let params = {
    appid:process.env.WX_APPID,
    secret:process.env.WX_SECRET,
    js_code:code,
    grant_type:'authorization_code'
  }

  const response = await cloud.fetch({
    url:'https://api.weixin.qq.com/sns/jscode2session',
    method:'get',
    params:params
  })
  if (!(response.status===200)){
    return fail("微信请求失败")
  }
  let data = response.data
  // @ts-ignore
  if (nw.util.isNull(data.openid)){
    return fail("微信授权失败")
  }
  console.log("返回的数据==========")
  console.log(data)
  /**
   * {
   * "openid":"xxxxxx",
   * "session_key":"xxxxx",
   * "unionid":"xxxxx",
   * "errcode":0,
   * "errmsg":"xxxxx"
   * }
   */
  //根据unionid得到user信息
  let user = await nw.db.findByWhereJson({
    dbName:"user",
        // @ts-ignore
    whereJson:{openId:data.openid}
  })
  if (nw.util.isNull(user)){
    //保存一个新的数据结构
    user = {
      userType:0,
      photoUrl:'',
      nickName:'张三',
      idNo:'',
      sex:0,
      phone:'',
      memo:'',
      openId:data.openid,
      unionId:data.unionid,
      isNew:1,
      createTime:new Date(),
      updateTime:new Date(),
      deleted:0
    }
    let id = await nw.db.add({
      dbName:"user",
      dataJson:user
    })
    if (nw.util.isNull(id)){
      return fail("创建用户失败")
    }
    user._id = id
  }
  //生产token
  let payload = {
    admin:user._id,
    // 默认 token 有效期为 7 天，请务必提供此 `exp` 字段，详见 JWT 文档。
    exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7,
  }
  const access_token = cloud.getToken(payload);
  //更新登录时间
  await nw.db.update({
    dbName:"user",
    whereJson:{
      _id: _.eq(user._id),
    },
    dataJson:{
      token:access_token,
      loginTime:new Date()
    }
  });


  let result = {token:access_token,user:user}
  //查询团长数据
  let queryData = {deleted:0,userId:user._id,isDefault:1}
  let userDelivery = await nw.db.findByWhereJson({
    dbName:"userDelivery",
    whereJson:queryData
  })
  if (!nw.util.isNull(userDelivery)&&!nw.util.isNull(userDelivery.leaderId)){
    //根据id查询团长数据
    let leader = await nw.db.findById({
      dbName:"leader",
      id:userDelivery.leaderId
    })
    if (!nw.util.isNull(leader)){
      let leaderAddressVo = {
        userId:leader.userId,
        leaderId:leader._id,
        leaderName:leader.name,
        leaderPhone:leader.phone,
        wareId:leader.wareId,
        storePath:leader.storePath
      }
      // @ts-ignore
      result.leaderAddressVo = leaderAddressVo
    }
  }

  return ok(result)
}
